/**
 * 
 */
package com.xb.cloud.product.merchant.service.impl;

import java.math.BigDecimal;
import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.xb.cloud.common.client.bo.PageBo;
import com.xb.cloud.common.constant.DbConstants;
import com.xb.cloud.common.model.PageParam;
import com.xb.cloud.order.service.client.ProductStockService;
import com.xb.cloud.product.merchant.inner.service.ProductSkuExtDescInnerService;
import com.xb.cloud.product.merchant.inner.service.ProductSkuExtPicInnerService;
import com.xb.cloud.product.merchant.inner.service.ProductSkuInnerService;
import com.xb.cloud.product.merchant.inner.service.ProductSkuPriceInnerService;
import com.xb.cloud.product.merchant.service.client.ProductSkuManageService;
import com.xb.cloud.product.merchant.service.client.bo.EndMerchantUserBo;
import com.xb.cloud.product.merchant.service.client.bo.ProductSkuBo;
import com.xb.cloud.product.merchant.service.client.input.bo.ProductSkuInputBo;
import com.xb.cloud.product.merchant.service.client.input.bo.ProductSkuPicInputBo;
import com.xb.cloud.product.service.business.model.ProductSku;
import com.xb.cloud.product.service.business.model.ProductSkuExample;
import com.xb.cloud.product.service.business.model.ProductSkuExample.Criteria;
import com.xb.cloud.product.service.business.model.ProductSkuExamplePaged;
import com.xb.cloud.product.service.business.model.ProductSkuPrice;
import com.xb.cloud.product.service.business.model.ProductSkuPriceExample;
import com.xb.cloud.product.service.business.model.mapper.ProductSkuMapper;
import com.xb.cloud.product.service.business.model.mapper.ProductSkuPriceMapper;
import com.xb.cloud.service.client.ServiceReturnCodes;
import com.xb.cloud.service.client.ServiceReturnInfo;
import com.xb.cloud.service.client.ServiceReturnUtils;

/**
 * 商家端sku管理服务类
 * 
 * @author kexue
 *
 */
@Service
public class ProductSkuManageServiceImpl extends AbstractService implements ProductSkuManageService {
	private static final Logger LOGGER = LoggerFactory.getLogger(ProductSkuManageServiceImpl.class);

	@Resource
	private ProductSkuMapper productSkuMapper;

	@Resource
	private ProductSkuPriceMapper productSkuPriceMapper;
	
	@Autowired
	private ProductStockService productStockService;
	
	@Resource
	private ProductSkuInnerService  productSkuInnerService;
	
	@Resource
	private ProductSkuExtPicInnerService productSkuExtPicInnerService;

	@Resource
	private ProductSkuPriceInnerService productSkuPriceInnerService;

	@Resource
	private ProductSkuExtDescInnerService productSkuExtDescInnerService;
	
	/**
	 * 获取仓库中sku列表
	 * 
	 * @param endMerchantUserBo
	 * @param isCanSale
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	public ServiceReturnInfo getSkuListByIsCanSale(EndMerchantUserBo endMerchantUserBo, byte isCanSale, Integer pageNum,
			Integer pageSize) {

		PageBo<ProductSkuBo> pageBo = new PageBo<ProductSkuBo>();

		ProductSkuExamplePaged skuExamplePaged = new ProductSkuExamplePaged();
		
		skuExamplePaged.setIsDeleted(DbConstants.IS_DELETED_FALSE);
		skuExamplePaged.setIsEnabled(DbConstants.TRUE);

		skuExamplePaged.setMerchantId(endMerchantUserBo.getMerchantId());
		skuExamplePaged.setShopId(endMerchantUserBo.getShopId());
		skuExamplePaged.setIsCanSale(isCanSale);

		int count = (int) productSkuMapper.countSkuListByIsCanSale(skuExamplePaged);
		if (count > 0) {
			skuExamplePaged.setPageParam(PageParam.resetPageParam(pageNum, pageSize));
			List<ProductSkuBo> productSkuBoList = productSkuMapper.selectSkuListByIsCanSale(skuExamplePaged);

			pageBo.setRows(productSkuBoList);
			pageBo.setTotal(count);
		}
		return ServiceReturnUtils.success(pageBo);
	}

	/**
	 * 上架、
	 * 
	 * @param endMerchantUserBo
	 * @return
	 */
	public ServiceReturnInfo skuUp(EndMerchantUserBo endMerchantUserBo, Long skuId) {
		// 检查
		ProductSkuExample skuExample = new ProductSkuExample();
		Criteria skuCriteria = skuExample.createCriteria();
		skuCriteria.andIsDeletedEqualTo(DbConstants.IS_DELETED_FALSE);
		skuCriteria.andIsEnabledEqualTo(DbConstants.TRUE);
		skuCriteria.andIsCanSaleEqualTo(DbConstants.PRODUCT_SKU_CAN_NOT_SALE);
		skuCriteria.andIdEqualTo(skuId);
		List<ProductSku> skuList = productSkuMapper.selectByExample(skuExample);

		if (skuList == null || skuList.size() <= 0) {
			LOGGER.error("上架失败，商品sku不存在");
			return ServiceReturnUtils.error(ServiceReturnCodes.PRODUCT_MANAGE_SKU_NOT_EXIST_OR_ALREADY_UP);
		}

		// 上架
		ProductSku recordSelective = new ProductSku();
		recordSelective.setId(skuId);
		recordSelective.setIsCanSale(DbConstants.PRODUCT_SKU_CAN_SALE);

		recordSelective.setUpdateTime(timeService.getDate());
		recordSelective.setUpdateUserId(endMerchantUserBo.getId());
		recordSelective.setUpdateUserName(endMerchantUserBo.getLoginName());
		int updateRow = productSkuMapper.updateByExampleSelective(recordSelective, skuExample);
		if (updateRow > 0) {
			return ServiceReturnUtils.success();
		} else {
			LOGGER.error("上架失败，商品sku不存在");
			return ServiceReturnUtils.error(ServiceReturnCodes.PRODUCT_MANAGE_SKU_NOT_EXIST_OR_ALREADY_UP);
		}
	}

	/**
	 * 下架、
	 * 
	 * @param endMerchantUserBo
	 * @return
	 */
	public ServiceReturnInfo skuDown(EndMerchantUserBo endMerchantUserBo, Long skuId) {
		// 检查
		ProductSkuExample skuExample = new ProductSkuExample();
		Criteria skuCriteria = skuExample.createCriteria();
		skuCriteria.andIsDeletedEqualTo(DbConstants.IS_DELETED_FALSE);
		skuCriteria.andIsEnabledEqualTo(DbConstants.TRUE);
		skuCriteria.andIsCanSaleEqualTo(DbConstants.PRODUCT_SKU_CAN_SALE);
		skuCriteria.andIdEqualTo(skuId);
		List<ProductSku> skuList = productSkuMapper.selectByExample(skuExample);

		if (skuList == null || skuList.size() <= 0) {
			LOGGER.error("下架失败，商品sku不存在");
			return ServiceReturnUtils.error(ServiceReturnCodes.PRODUCT_MANAGE_SKU_NOT_EXIST_OR_ALREADY_DOWN);
		}

		// 下架
		ProductSku recordSelective = new ProductSku();
		recordSelective.setId(skuId);
		recordSelective.setIsCanSale(DbConstants.PRODUCT_SKU_CAN_NOT_SALE);

		recordSelective.setUpdateTime(timeService.getDate());
		recordSelective.setUpdateUserId(endMerchantUserBo.getId());
		recordSelective.setUpdateUserName(endMerchantUserBo.getLoginName());
		int updateRow = productSkuMapper.updateByExampleSelective(recordSelective, skuExample);
		if (updateRow > 0) {
			return ServiceReturnUtils.success();
		} else {
			LOGGER.error("下架失败，商品sku不存在");
			return ServiceReturnUtils.error(ServiceReturnCodes.PRODUCT_MANAGE_SKU_NOT_EXIST_OR_ALREADY_DOWN);
		}
	}

	// 修改价格
	public ServiceReturnInfo updatePrice(EndMerchantUserBo endMerchantUserBo, Long skuId, BigDecimal price) {
		// 检查
		ProductSkuPriceExample skuPriceExample = new ProductSkuPriceExample();
		com.xb.cloud.product.service.business.model.ProductSkuPriceExample.Criteria skuPriceCriteria = skuPriceExample.createCriteria();
		skuPriceCriteria.andIsDeletedEqualTo(DbConstants.IS_DELETED_FALSE);
		skuPriceCriteria.andSkuIdEqualTo(skuId);
		List<ProductSkuPrice> skuPriceList = productSkuPriceMapper.selectByExample(skuPriceExample);
		if (skuPriceList == null || skuPriceList.size() <= 0) {
			LOGGER.error("此商品已经不存在");
			return ServiceReturnUtils.error(ServiceReturnCodes.PRODUCT_MANAGE_SKU_NOT_EXIST);
		}

		// 改价
		ProductSkuPrice recordSelective = new ProductSkuPrice();
		recordSelective.setSkuId(skuId);
		recordSelective.setPriceSale(price);

		recordSelective.setUpdateTime(timeService.getDate());
		recordSelective.setUpdateUserId(endMerchantUserBo.getId());
		recordSelective.setUpdateUserName(endMerchantUserBo.getLoginName());
		int updateRow = productSkuPriceMapper.updateByExampleSelective(recordSelective, skuPriceExample);
		if (updateRow > 0) {
			return ServiceReturnUtils.success();
		} else {
			LOGGER.error("修改失败");
			return ServiceReturnUtils.error(ServiceReturnCodes.SYSTEM_EXCEPTION);
		}
	}

	@Override
	public ServiceReturnInfo skuDelete(EndMerchantUserBo endMerchantUserBo, Long skuId) {
		ProductSkuExample skuExample = new ProductSkuExample();
		Criteria skuCriteria = skuExample.createCriteria();
		skuCriteria.andIsDeletedEqualTo(DbConstants.IS_DELETED_FALSE);
		skuCriteria.andIsEnabledEqualTo(DbConstants.TRUE);
		skuCriteria.andIdEqualTo(skuId);
		List<ProductSku> skuList = productSkuMapper.selectByExample(skuExample);

		if (skuList == null || skuList.size() <= 0) {
			LOGGER.error("商品sku不存在");
			return ServiceReturnUtils.error(ServiceReturnCodes.PRODUCT_MANAGE_SKU_DONOT_EXIST);
		}

		// 下架
		ProductSku recordSelective = new ProductSku();
		recordSelective.setId(skuId);
		recordSelective.setIsCanSale(DbConstants.PRODUCT_SKU_CAN_NOT_SALE);
		recordSelective.setIsDeleted(DbConstants.IS_DELETED_TRUE);
		recordSelective.setUpdateTime(timeService.getDate());
		recordSelective.setUpdateUserId(endMerchantUserBo.getId());
		recordSelective.setUpdateUserName(endMerchantUserBo.getLoginName());
		int updateRow = productSkuMapper.updateByExampleSelective(recordSelective, skuExample);
		boolean isDelete = false;
		if (updateRow > 0) {
			isDelete = true;
		} else {
			LOGGER.error("删除失败，商品sku不存在");
			return ServiceReturnUtils.error(ServiceReturnCodes.PRODUCT_MANAGE_SKU_DONOT_EXIST);
		}
		if(isDelete)  {
			ProductSkuPriceExample price_example = new ProductSkuPriceExample();
			price_example.createCriteria().andSkuIdEqualTo(skuId);
			
			//删除价格
			ProductSkuPrice price = new ProductSkuPrice();
			price.setSkuId(skuId);
			price.setIsDeleted(DbConstants.IS_DELETED_TRUE);
			price.setIsEnabled(DbConstants.PRODUCT_SKU_NOT_ENABLED);
			productSkuPriceMapper.updateByExampleSelective(price, price_example);
			
			//删除库存
			ServiceReturnInfo deleteStockInfo = productStockService.deleteStock(endMerchantUserBo, skuList.get(0).getShopId(), skuList.get(0).getProductId());
			if(ServiceReturnUtils.isError(deleteStockInfo)) {
				LOGGER.error("删除库存失败");
			}
		}
		return ServiceReturnUtils.success();
	}

	/**
	 * 更新Sku (product库相关表的更新/插入在一个事务里面)
	 * 
	 * @param productId
	 *            ： 商品id
	 * @param shopId:
	 *            店铺 Id
	 * @param detailContent
	 *            : 图文详情的html
	 * @param skuNameCn
	 * @param skuTitleSub
	 * @param price
	 *            : 价格
	 * @param stock:库存
	 */
	@Transactional(propagation = Propagation.REQUIRED,value="transactionManager_product")
	@Override
	public ServiceReturnInfo skuUpdate(EndMerchantUserBo endMerchantUserBo, Long productId,
			List<ProductSkuPicInputBo> skuPics, String detailContentJson,
			ProductSkuInputBo skuInput, BigDecimal priceSale, BigDecimal priceMarket) {

		// 1.更新sku
		Long productSkuId = productSkuInnerService.updateSku(skuInput, endMerchantUserBo);

		// 2.更新图片
		productSkuExtPicInnerService.updateSkuExtPics(skuPics, productSkuId,
			endMerchantUserBo);

		// 3.更新价格
		productSkuPriceInnerService.updateSkuPrice(priceSale,priceMarket, productSkuId, endMerchantUserBo);

		// 4.更新文本描述
		productSkuExtDescInnerService.updateSkuExtDesc(detailContentJson, productSkuId,
			endMerchantUserBo);
		 
		return ServiceReturnUtils.success(productSkuId);
	}
}
